#!/bin/bash
set -e

echo "========== PDF2PPT Linux 服务安装脚本 =========="

# 检查 JAVA_HOME
if [[ -z "$JAVA_HOME" ]]; then
  echo "[错误] JAVA_HOME 环境变量未设置，请先设置 JAVA_HOME。"
  exit 1
fi

# 检查 npm 是否安装
if ! command -v npm >/dev/null 2>&1; then
  echo "[错误] 未检测到 npm，请先安装 Node.js 和 npm。"
  exit 1
fi

# 1. 构建后端 fat jar
cd backend
./mvnw clean package -DskipTests
cd ..

# 2. 注册后端 systemd 服务
SERVICE_NAME=pdf2ppt-backend
JAR_PATH="$(pwd)/backend/target/pdf-to-ppt-1.0.0.jar"
SERVICE_FILE="/etc/systemd/system/$SERVICE_NAME.service"

sudo bash -c "cat > $SERVICE_FILE" <<EOF
[Unit]
Description=PDF2PPT 后端服务
After=network.target

[Service]
Type=simple
WorkingDirectory=$(pwd)/backend
ExecStart=$JAVA_HOME/bin/java -jar $JAR_PATH
Restart=on-failure
User=$(whoami)

[Install]
WantedBy=multi-user.target
EOF

sudo systemctl daemon-reload
sudo systemctl enable $SERVICE_NAME
sudo systemctl restart $SERVICE_NAME

# 3. 注册前端 systemd 服务（开发模式）
FRONTEND_SERVICE=pdf2ppt-frontend-dev
FRONTEND_DIR="$(pwd)/frontend"
FRONTEND_SERVICE_FILE="/etc/systemd/system/$FRONTEND_SERVICE.service"
NPM_PATH=$(command -v npm)
USER=$(whoami)

sudo bash -c "cat > $FRONTEND_SERVICE_FILE" <<EOF
[Unit]
Description=PDF2PPT 前端开发服务
After=network.target

[Service]
Type=simple
WorkingDirectory=$FRONTEND_DIR
ExecStart=$NPM_PATH run dev
Restart=on-failure
User=$USER

[Install]
WantedBy=multi-user.target
EOF

sudo systemctl daemon-reload
sudo systemctl enable $FRONTEND_SERVICE
sudo systemctl restart $FRONTEND_SERVICE

echo
echo "[完成] 后端和前端（开发模式）已作为 systemd 服务运行。"
echo "前端地址: http://<服务器IP>:5173"
echo "后端API: http://<服务器IP>:8080"
echo "如需管理服务，可用：sudo systemctl [start|stop|restart|status] pdf2ppt-backend/pdf2ppt-frontend-dev" 